package vn.demand.dragon.view
{
	import flash.events.Event;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import vn.demand.dragon.MarketingApplicationFacade;
	import vn.demand.dragon.model.CompanyProxy;
	import vn.demand.dragon.model.MasterdataProxy;
	import vn.demand.dragon.view.components.CustomerSearch;
	
	public class CustomerSearchMediator extends Mediator
	{
		public static const NAME:String = "CustomerSearchMediator";
		
		private var masterdataProxy:MasterdataProxy;
		private var customerProxy:CompanyProxy;
		
		private var viewCreated:Boolean = false;
		
		public function CustomerSearchMediator(mediatorId:String, view:Object)
		{
			super(mediatorId, view);
			
			masterdataProxy = facade.retrieveProxy(MasterdataProxy.NAME) as MasterdataProxy;
			customerProxy = facade.retrieveProxy(CompanyProxy.NAME) as CompanyProxy;
			
			searchForm.addEventListener('viewCreated', onViewCreated);
			searchForm.addEventListener('onSearch', onSearch);
			searchForm.addEventListener('onReset', onReset);
		}
		
		public function onViewCreated(event:Event):void {
			viewCreated = true;
			if (masterdataProxy.masterdataLoaded) {
				prepareData();
			}
		}
		 
		public function prepareData():void {
			searchForm.c_status.dataProvider = masterdataProxy.companyStatusesDP;
			searchForm.c_type.dataProvider = masterdataProxy.companyTypesDP;
			
			searchForm.c_status.selectedIndex = 0;
			searchForm.c_type.selectedIndex = 0;
		} 
		
		public function onSearch(event:Event):void {
			var o:Object = {};
            o.company_code = searchForm.c_code.text;
			o.company_name = searchForm.c_name.text;
			o.company_exact_code = searchForm.c_exact_code.text;
			o.company_status = searchForm.c_status.selectedData;
			o.company_type2 = searchForm.c_type.selectedData;
            
            customerProxy.loadCustomers(o);
		}
		
		public function onReset(event:Event):void {
			searchForm.c_code.text = '';
			searchForm.c_name.text = '';
			searchForm.c_exact_code.text = '';
			searchForm.c_status.selectedIndex = 0;
			searchForm.c_type.selectedIndex = 0;
			customerProxy.loadCustomers();
		}
		
		override public function listNotificationInterests():Array 
        {
            return [ MarketingApplicationFacade.LOAD_MASTERDATA_SUCCESS,   
            ];
        }
        
        override public function handleNotification( note:INotification ):void 
        {
            switch ( note.getName() ) 
			{
				case MarketingApplicationFacade.LOAD_MASTERDATA_SUCCESS:
					onViewCreated(null);
					break;
			}
        }
		
		public function get searchForm():CustomerSearch {
			return viewComponent as CustomerSearch;
		}

	}
}